<template>
  <view class="chat-container">
    <!-- 聊天区域 -->
    <scroll-view 
      class="chat-area" 
      scroll-y
      :scroll-top="scrollTop"
      scroll-with-animation
      @scrolltoupper="loadMore"
      @scroll="handleScroll"
    >
      <!-- <uni-load-more 
        v-if="loading"
        status="loading" 
        :icon-size="16"
        :content-text="{
          contentdown: '上拉显示更多',
          contentrefresh: '正在加载...',
          contentnomore: '没有更多了'
        }"
      /> -->
      <view 
        class="chat-message" 
        v-for="(msg, index) in messages" 
        :key="index"
      >
        <image 
          v-if="!msg.isSelf"
          class="avatar" 
          :src="avatar1" 
        />
        <view class="message-bubble" :class="{ 'self': msg.isSelf }">
          {{ msg.content }}
        </view>
        <image 
          v-if="msg.isSelf"
          class="avatar self-avatar" 
          :src="avatar2" 
        />
      </view>
      <view style="height: 10px;"></view>
    </scroll-view>
  </view>
  <!-- 输入框区域 -->
  <view class="input-area">
    <input 
      class="input-box" 
      v-model="inputText" 
      placeholder="输入消息..."
      @confirm="sendMessage"
    />
    <button class="send-btn" @click="sendMessage">发送</button>
  </view>
</template>

<script setup>
import { ref, watch, computed, onMounted, nextTick } from 'vue'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { http } from '../../../utils/request'
import { formatTimestamp } from '../../../utils/dateUtils'

const scrollTop = ref(0)
const username = ref('')
const avatar1 = ref('')
const avatar2 = ref('')
const inputText = ref('')
const allMessages = ref([])
const pageSize = 15
const currentPage = ref(1)
const loading = ref(false)
const noMore = ref(false)
const scrollHeight = ref(0)
const scrollTopBeforeLoad = ref(0)
const afterLoadHeight = ref(0)

const messages = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  return [...allMessages.value].slice(0, start + pageSize).reverse()
})

const scrollToBottom = () => {
  scrollTop.value = 999999
}

const handleScroll = (e) => {
  scrollHeight.value = e.detail.scrollHeight
}

const loadMore = () => {
  if (loading.value || noMore.value) return
  
  loading.value = true
  const beforeLoadHeight = scrollHeight.value
  if(afterLoadHeight.value)  scrollTop.value = afterLoadHeight.value - beforeLoadHeight
  const total = allMessages.value.length
  const loaded = currentPage.value * pageSize
  
  if (loaded >= total) {
    noMore.value = true
    loading.value = false
    return
  }
  
  setTimeout(() => {
    currentPage.value++
    loading.value = false
    nextTick(() => {
      afterLoadHeight.value = scrollHeight.value
    })
  }, 1000) // 模拟加载延迟
}

onMounted(() => {
  scrollToBottom()
})

const userId = ref(null)
const myId = ref(null)

uni.$on('newMessage', (message) => {
  console.log('Received message:', message);
	if(message.fromUserId!==userId.value)	return
	allMessages.value.unshift({
		content: message.content,
		isSelf: false
	})
});

onLoad(async(options) => {
	
	
	try {
		avatar1.value = options.avatarUrl
		
		userId.value = options.userId
		myId.value= uni.getStorageSync('userId')
		
		const userInfo = await http.get('/users/info', {userId:myId.value})
		console.log(userInfo);
		avatar2.value = userInfo.avatarUrl
		uni.setNavigationBarTitle({
			title: options.userName
		})
		const res = await http.get('/api/messages/conversation',{
			userId : userId.value,
			yourId : myId.value
		})
		// console.log(res.messages);
		res.messages.map(item=>{
			console.log(item);
			allMessages.value.push({
				content: item.content,
				isSelf: myId.value===item.fromUserId
			})
		})
	} catch (e) {
		console.log("获取用户历史消息失败:",e);
	}
	
})

onUnload(async()=>{
	const res =await http.put('/api/messages/read',{
		toUserId: myId.value,
		fromUserId: userId.value
	})
})

const sendMessage = async () => {
  if (!inputText.value.trim()) return
  
  allMessages.value.unshift({
    content: inputText.value,
    isSelf: true
  })
	console.log("myId.value:",myId.value)
	const res  = await http.post('/api/messages/send',{
		fromUserId: myId.value,
		toUserId: userId.value,
		content: inputText.value
	},{
		header: {
		  'Content-Type': 'application/json'
		}
	})
	console.log(res);
  inputText.value = ''
  scrollToBottom()
  
}
</script>

<style>
.chat-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 70px);
  overflow: hidden;
}

.chat-area {
  flex: 1;
  overflow-y: auto;
  padding-top: 10px;
  box-sizing: border-box;
  background-color: #f1f1f1;
  display: flex;
  flex-direction: column-reverse;
}

.chat-message {
  margin-bottom: 15px;
  display: flex;
}

.message-bubble {
  max-width: 60%;
  padding: 8px 12px;
  border-radius: 4px;
  background-color: #fff;
  word-break: break-word;
}

.message-bubble.self {
  margin-left: auto;
  background-color: #95ec69;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin: 0 10px;
  align-self: flex-start;
}

.self-avatar {
  order: 1;
}

.input-area {
  position: fixed;
  bottom: 0;
  width: 100vw;
  box-sizing: border-box;
  display: flex;
  padding: 8px 16px;
  background-color: #fff;
}

.input-box {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-right: 8px;
}

.send-btn {
  padding: 0 15px;
  background-color: #07c160;
  color: white;
  border-radius: 4px;
}
</style>
